<?php
Globals::requireClass('Controller');
Globals::requireClass('Alipay');
Globals::requireModel('User');
Globals::requireTable('User');
Globals::requireTable('Product');
Globals::requireTable('Order');
Globals::requireTable('Account');
Globals::requireTable('Msg');
Globals::requireTable('Withdrawals');
Globals::requireTable('Vmoney');
Globals::requireTable('Vlevel');

class PayController extends Controller
{
	protected $UserTable;
	protected $ProductTable;
	protected $OrderTable;
	protected $AccountTable;
	protected $MsgTable;
	protected $WithdrawalsTable;
	protected $VmoneyTable;
	protected $VlevelTable;
	
	public static $defaultConfig = array(
		'viewEnabled'	=> false,
		'layoutEnabled'	=> false,
		'title'			=> null
	);
	
	public function __construct($config = null)
	{
	    $config['viewEnabled'] = false;
	    $config['layoutEnabled'] = false;
		parent::__construct($config);
		$this->UserTable          = new UserTable($config);
		$this->ProductTable       = new ProductTable($config);
		$this->OrderTable         = new OrderTable($config);
		$this->AccountTable       = new AccountTable($config);
		$this->MsgTable           = new MsgTable($config);
		$this->WithdrawalsTable   = new WithdrawalsTable($config);
		$this->VmoneyTable        = new VmoneyTable($config);
		$this->VlevelTable        = new VlevelTable($config);
		dolog(json_encode($_GET));
	}
	
	public function indexAction()
	{
		
	}
	
	/**
	 * 下单
	 * uid/token&machine_type
	 * aid
	 */
	public function onedayAction()
	{
	    $uid = $this->getParam('uid');
	    $token = $this->getParam('token');
	    $machine_type = $this->getParam('machine_type');
	    $usermodel = new UserModel($this->config);
	    $uid = $usermodel->getUserBase($uid, $token ,$machine_type);
	    $user = $this->UserTable->getRow($uid);
	    if($uid < 1 || $user['id'] < 1){
	        echo json_encode(array('returncode'=>-1,'orderid'=>''));
	        exit();
	    }
	    
	    $time = time();
	    $aid = $this->getIntParam('aid');
	    $account = $this->AccountTable->getRow($aid);
	    $product = $this->ProductTable->getRow($account['pid']);
	    if(empty($aid) || $account['status'] != 2 || $product['status'] != 1 || $account['nums_stock'] >= $account['nums_value'] || $account['endtime'] <= $time){
	        echo json_encode(array('returncode'=>-2,'orderid'=>''));
	        exit();
	    }
	    /*
	    $ispayed = $this->OrderTable->getRow(array('uid'=>$uid,'status'=>1,'aid'=>$aid));
	    if($ispayed['id'] > 0){
	        echo json_encode(array('returncode'=>-3,'orderid'=>''));
	        exit();
	    }
	    */
	    $time_day = strtotime(date('Y-m-d'));
	    $day_value = ($account['endtime'] - $time_day) / 86400;
	    $day_value = $day_value == (int)$day_value ? $day_value : (int)$day_value + 1;
		
	    $data['orderid'] = substr($time, -9) . mt_rand(10, 99);
	    $data['uid'] = $uid;
	    $data['pid'] = $account['pid'];
	    $data['aid'] = $aid;
	    $data['createtime'] = date('Y-m-d H:i:s');
	    $data['status'] = 0;
	    $data['money'] = round(DAY_MONEY * $day_value + 0.4 - $day_value / 1216,2);
	    $data['days'] = $day_value;
	    $data['endtime'] =$account['endtime'];
	    $data['uid_from'] = $account['uid'];
	    $this->OrderTable->add($data);
	    echo json_encode(array('returncode'=>0,'orderid'=>(string)$data['orderid']));
	    exit();
	}
	
	/**
	 * 支付成功
	 * orderid
	 * payorderid
	 * paytype
	 * sign
	 */
	public function payokAction()
	{
	    $orderid = $this->getParam('orderid');
	    $payorderid = $this->getParam('payorderid');
	    $paytype = $this->getParam('paytype');
	    $sign = $this->getParam('ordersign');
	    $time = time();
	    $date = date('Y-m-d H:i:s');
	    
	    $order = $this->OrderTable->getRow(array('orderid'=>$orderid));
	    $account = $this->AccountTable->getRow($order['aid']);
	    $user = $this->UserTable->getRow($account['uid']);//账号归属人
	    $product = $this->ProductTable->getRow($account['pid']);
	    $user_buyer = $this->UserTable->getRow($order['uid']);//账号购买者
	    
	    if($user['id'] < 1 || $user_buyer['id'] <1 || $order['id'] < 1 || $order['status'] != 0 || $account['id'] < 1 || $account['status'] != 2 || $account['nums_stock'] >= $account['nums_value'] || $account['endtime'] < $time){
	        echo json_encode(array('returncode'=>-1,'username'=>'','password'=>''));
	        exit();
	    }
	    /*
	    $new_num_arr = array();
	    $orderid_num = $orderid + 19921206;
	    for ($ii = 0 ; $ii < strlen($orderid_num) ; $ii++){
	        $tmp_num = substr($orderid_num, $ii , 1);
	        $new_num_arr[] = $tmp_num;
	    }
	    krsort($new_num_arr);
	    $new_num = '';
	    foreach ($new_num_arr as $v){
	        $new_num .= (string)$v;
	    }
	    if($sign != $new_num){
	        echo json_encode(array('returncode'=>-2,'username'=>'','password'=>''));
	        exit();
	    }
	    */
	    $paytypevalue = 0;
	    $paytype = empty($paytype) ? 'alipay' : $paytype;
	    if($paytype == 'alipay'){
	        $alipay = new Alipay();
	        $re = $alipay->queryone('',$payorderid);
	        $alipay_money = $re->response->trade->total_fee;
	        if($order['money'] != $alipay_money){
	            echo json_encode(array('returncode'=>-999,'username'=>'','password'=>''));
	            exit();
	        }
	        
	        $paytypevalue = 1;
	    }elseif($paytype == 'vmoney'){
	        $vcount = 0;
	        $listvalue = $this->VmoneyTable->listAllWithFields('money',array('uid'=>$user_buyer['id']));
	        foreach ($listvalue as $k=>$v){
	            $vcount += $v['money'];
	        }
	        if($vcount < $order['money']){
	            echo json_encode(array('returncode'=>-998,'username'=>'','password'=>''));
	            exit();
	        }
	        
	        $paytypevalue = 2;
	    }
	    
	    
	    $data['paytype'] = $paytypevalue;
	    $data['paytime'] = date('Y-m-d H:i:s');
	    $data['payorderid'] = $payorderid;
	    $data['status'] = 1;
	    $this->OrderTable->update($data,$order['id']);
	    
	    $user_data['money'] = $user['money'] + $order['money'];
	    $get_money = $order['money'] * 0.01;
	    $get_money = sprintf("%.2f", $get_money);
	    $get_money = $get_money < 0.01 ? 0.01 : $get_money;
	    
	    $account_data['nums_stock'] = $account['nums_stock'] + 1;
	    $this->AccountTable->update($account_data,$account['id']);
	    
	    if($account['nums_stock'] < $account['nums_show']){
	        /*
    	    $user_data['v_money'] = $user['v_money'] + $get_money;
    	    $this->UserTable->update($user_data,$user['id']);
    	    unset($user_data);
    	    $vmoney_data['uid'] = $user['id'];
    	    $vmoney_data['type'] = 1;
    	    $vmoney_data['money'] = $get_money;
    	    $vmoney_data['remark'] = '被购买账号获得V币'.$get_money.'，'.$product['name'].','.$account['username'];
    	    $this->VmoneyTable->add($vmoney_data);
    	    unset($vmoney_data);
    	    */
    	    $vlevel_data['uid'] = $user['id'];
    	    $vlevel_data['type'] = 1;
    	    $vlevel_data['level'] = $get_money;
    	    $vlevel_data['remark'] = '被购买账号获得V级'.$get_money.'，'.$product['name'].','.$account['username'];
    	    $this->VlevelTable->add($vlevel_data);
    	    unset($vlevel_data);
            
    	    $msg_data['uid'] = $user['id'];
    	    $msg_data['createdate'] = date('Y-m-d H:i:s');
    	    $msg_data['msg'] = '又来收入了！有人购买了您的账号！'.$product['name'].','.$account['username'];
    	    $msg_data['status'] = 0;
    	    $this->MsgTable->add($msg_data);
    	    
    	    $exreas = array(
    	        'income' => '离土豪又近了一步哦！',
    	        'pushtype' => 2,
    	        'content' => '离土豪又近了一步哦！',
    	        //'customfield' => 'http://mp.weixin.qq.com/s/***UserCenterRevenueVipViewController***'
    	        'customfield' => ''
    	    );
    	    do_jpush($user['id'],'又来收入了',$exreas);
            
    	    
			$microsecond = explode(' ', microtime()); //' '中间是一个空格 
			$ms = explode('.',$microsecond[0]);
			$customfield = array(
				'nickName' => "用户ID：{$user_buyer['id']}",
				'type' => '1',
				'icon' => 'temporary11',
				'messageSection' => $user_buyer['id'],
				'time' => $date,
				'chatId' => $date.$ms[1]
			);
			
			$message = "我在《小树林》APP购买了您提供的{$product['name']}账号\n账号：{$account['username']}\n密码：{$account['password']}\n如果此账号需要验证码登录请回复:\n《如需验证码登录我会发你》\n如果没有及时处理用户问题，被用户投诉后将扣除您收入的0.1元";
			$exreas = array(
				'income' => $message,
				'pushtype' => 14,
				'content' => $message,
				'customfield' => json_encode($customfield)
			);
			do_jpush($user['id'],"用户ID：{$user_buyer['id']}，购买了您的{$product['name']}账号，如需验证码登录请点击回复沟通",$exreas);
            
	    }else{
	        $this->OrderTable->update(array('uid_from'=>1,'o_uid_from'=>$order['uid_from']),$order['id']);
	    }
	    
	    $user_data['v_money'] = $user_buyer['v_money'] + $get_money;
	    $this->UserTable->update($user_data,$order['uid']);
	    unset($user_data);
	    
	    $get_money = round($order['money'] * 0.02,2);
	    $get_money = $get_money < 0.01 ? 0.01 : $get_money;
	    
	    $vmoney_data['uid'] = $user_buyer['id'];
	    $vmoney_data['type'] = 1;
	    $vmoney_data['money'] = $get_money;
	    $vmoney_data['remark'] = '购买账号获得V币'.$get_money.'，'.$product['name'].','.$account['username'];
	    $this->VmoneyTable->add($vmoney_data);
	    
	    $vlevel_data['uid'] = $user_buyer['id'];
	    $vlevel_data['type'] = 1;
	    $vlevel_data['level'] = $get_money;
	    $vlevel_data['remark'] = '购买账号获得V级'.$get_money.'，'.$product['name'].','.$account['username'];
	    $this->VlevelTable->add($vlevel_data);
	    
	    if($paytype == 'vmoney'){
	        $user_data['v_money'] = $user_data['v_money'] - $order['money'];
	        $this->UserTable->update($user_data,$order['uid']);
	        
	        $vmoney_data['uid'] = $user_buyer['id'];
	        $vmoney_data['type'] = 4;
	        $vmoney_data['money'] = (0-$order['money']);
	        $vmoney_data['remark'] = '购买账号消耗V币'.$order['money'];
	        $this->VmoneyTable->add($vmoney_data);
	        
	    }
	    
	    echo json_encode(array('returncode'=>0,'username'=>(string)$account['username'],'password'=>(string)$account['password']));
	    exit();
	}
	
	protected function out()
	{
		parent::out();
	}
}

Config::extend('PayController', 'Controller');
